<?php

namespace app\service;

use app\model\Category as CategoryModel;

class CategoryService
{
    protected $model;

    public function __construct(){
        $this->model = app()->make(CategoryModel::class);
    }

    /**
     * @param array $where
     * @return CategoryModel|CategoryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryList($where = [])
    {
        $categoryList = $this->model->where($where)->order('sort desc')->select();
        $newCategoryList = array();
        foreach ($categoryList as $key=> $item) {
            if ($item->parent_id == 0) {
                $childrenList = array();
                foreach ($categoryList as $key2=> $item2) {
                    if ($item2['parent_id'] == $item['id']) {
                        $childrenList[] = $item2;
                    }
                }
                $item['childrenList'] = $childrenList;
                $newCategoryList[] = $item;
            }
        }
        return $newCategoryList;
    }

    /**
     * @param array $where
     * @return CategoryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryListByWhere(array $where)
    {
        return $this->model->where($where)->select();
    }

    /**
     * 查询分类详情
     *
     * @param int $id
     * @return CategoryModel|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryDetail(int $id){
        return $this->model->where('id', $id)->find();
    }
    public function save(array $data): bool
    {
        $result = null;
        if (empty($data['id'])) {
            $result = $this->model->insert($data);
        } else {
            $result = $this->model->where('id', $data['id'])->save($data);
        }
        return $result != null;
    }

    /**
     * @param array $idArr
     * @return CategoryModel[]|array|\think\Collection
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function queryListByIdArr(array $idArr)
    {
        return $this->model->where('id', 'in' ,$idArr)->select();
    }

}